package counter.com.baomidou.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import counter.com.baomidou.entity.Targetinfo;
import counter.com.baomidou.mapper.TargetinfoMapper;
import counter.com.baomidou.service.ITargetinfoService;
import counter.com.common.Result;
import counter.com.connproperty.targetinfo.TargetAddProperty;
import counter.com.connproperty.targetinfo.TargetDeleteProperty;
import counter.com.connproperty.targetinfo.TargetSearchProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author jobob
 * @since 2020-10-01
 */
@RestController
@RequestMapping("/targetinfo")
public class TargetinfoController {
    @Autowired
    ITargetinfoService service;

    @Autowired
    TargetinfoMapper mapper;

    @PostMapping("/search")
    public Result search(@RequestBody TargetSearchProperty data) {
        Page<Targetinfo> page = new Page<>(data.getPage(), data.getPagesize());
        LambdaQueryWrapper<Targetinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(Targetinfo::getId);
        IPage<Targetinfo> iPage = service.page(page, wrapper);
        return Result.success(iPage);
    }

    @PostMapping("/add")
    public Result add(@RequestBody TargetAddProperty data) {
        String targetIp = data.getIp();
        LambdaQueryWrapper<Targetinfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Targetinfo::getIp, targetIp);
        Targetinfo one = service.getOne(wrapper);
        if (one != null) {
            return Result.fail("已经存在重复的IP地址");
        }
        Targetinfo targetinfo = new Targetinfo();
        targetinfo.setIp(data.getIp());
        targetinfo.setType(data.getType());
        targetinfo.setDomain(data.getDomain());
        targetinfo.setUrl(data.getUrl());
        targetinfo.setCreatedtime(LocalDateTime.now());
        if (service.save(targetinfo)) {
            return Result.success("成功添加");
        } else {
            return Result.fail("添加失败");
        }
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody TargetDeleteProperty data) {
        Integer[] ids = data.getIds();
        List<Integer> removeIds = Arrays.asList(ids);
        /**
         * 如果至少删除成功了一个对象，最后的结果就会返回true
         */
        if (service.removeByIds(removeIds)) {
            return Result.success("删除成功");
        } else {
            return Result.fail("失败");
        }
    }
}
